package post

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/cachex"
	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/mqueuex"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/lib/forumreaction"
	"mall/service/forum/api/internal/lib/userrank"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/forum/rpc/forumclient"
	"mall/service/user/rpc/userclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPostListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostListLogic {
	return &GetPostListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 香评列表 ##25.03.22## 历史遗留文件，暂不处理
// Todo: 借鉴 l.getUserRankMap
// Todo: 借鉴 l.getPostLikeBatch
func (l *GetPostListLogic) GetPostList(req *types.PostListReq) (*types.PostListInfo, error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var uid uint64 // 查询谁的记录
	if req.UserId != nil && *req.UserId > 0 {
		uid = *req.UserId
	} else {
		uid = userId
	}
	var private bool = true // 是本人的记录
	if uid != userId {      // 不是本人的记录
		private = false
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var filters []string
	filters = append(filters, "ForumId,equalTo:"+strconv.FormatInt(l.svcCtx.Config.Query.PostForumId, 10))
	if req.Filter != nil && len(strings.TrimSpace(*req.Filter)) > 0 {
		filterMap := util.GetFilterMap(strings.TrimSpace(*req.Filter))
		for key, val := range filterMap {
			switch key {
			case "sticky":
				filters = append(filters, "Sticky,equalTo:"+val)
			}
		}
	}

	preload := "forumPost:Id,AuthorId,ParentId,AverageRating,Sticky"
	eagerLoad := "forumPost:forumMedia"
	var skipParent bool // 不用再返回香水信息了
	var skipLevel bool
	if req.ParentId != nil && *req.ParentId > 0 { // 指定香水的香评
		private = false // 大家的香评
		skipParent = true
		preload += ",AuthorName,AuthorAvatar,AuthorIp,AuthorLevel"
		eagerLoad += ",total"
		filters = append(filters, "ParentId,equalTo:"+strconv.FormatUint(*req.ParentId, 10))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	} else if private { // 我的香评
		skipLevel = true
		preload += ",Status"
		filters = append(filters, "AuthorId,equalTo:"+strconv.FormatUint(uid, 10))
		filters = append(filters, "Status,notEqualTo:"+strconv.FormatInt(int64(globalkey.StatusDeleted), 10))
	} else { // 别人的香评
		skipLevel = true
		filters = append(filters, "AuthorId,equalTo:"+strconv.FormatUint(uid, 10))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	}
	preload += ",ContentHtml,CommentStatus,CommentCount,CreatedAt;forumMedia:Id,Uid,Url,Thumbnail"

	var sorter *string
	if req.Sorter != nil {
		sorter = pointy.GetPointer(strings.TrimSpace(*req.Sorter))
	}

	res, err := l.svcCtx.ForumRpc.GetPostList(l.ctx, &forumclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     sorter,
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}
	resp := &types.PostListInfo{
		BaseListInfo: types.BaseListInfo{
			Total:           res.Total,
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		var perfumeMap map[uint64]*types.KbEntryInfo
		if !skipParent {
			var pids []string
			for _, v := range res.List {
				if v.ParentId != nil && *v.ParentId > 0 {
					pids = append(pids, strconv.FormatUint(*v.ParentId, 10))
				}
			}

			if len(pids) == 0 {
				return resp, nil
			}

			perfumeMap, err = l.getPerfumeMap(pids)
			if err != nil {
				return nil, err
			}

			if perfumeMap == nil {
				return resp, nil
			}
		}

		var userRankMap map[uint32]*types.UserRankInfo
		if !skipLevel {
			userRankMap = l.getUserRankMap(userId)
		}
		var postIds []string
		for _, v := range res.List {
			if v.Id != nil && *v.Id > 0 {
				postIds = append(postIds, strconv.FormatUint(*v.Id, 10))
			}
		}
		likeMap := l.getPostLikeBatch(postIds, strconv.FormatUint(userId, 10))

		for _, v := range res.List {
			var parent *types.KbEntryInfo
			if !skipParent && perfumeMap != nil && v.ParentId != nil && *v.ParentId > 0 {
				if pv, ok := perfumeMap[*v.ParentId]; ok {
					parent = pv
				}
			}

			var photos []*types.MediaInfo
			if len(v.Media) > 0 {
				for _, m := range v.Media {
					var url string
					if m.Url != nil && len(*m.Url) > 0 {
						url = *m.Url
					}
					if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
						url = *m.Uri
					}
					var thumbnail *bool
					if m.Thumbnail != nil {
						thumbnail = pointy.GetPointer(*m.Thumbnail > 0)
					}
					photos = append(photos, &types.MediaInfo{
						Uid:       m.Uid,
						Id:        m.Id,
						Url:       pointy.GetPointer(url),
						Thumbnail: thumbnail,
						AltText:   m.AltText,
						Details:   m.MetaData,
					})
				}
			}

			var isLiked *bool
			var likeCount *uint64
			if likeMap != nil && v.Id != nil && *v.Id > 0 {
				if likeStatus, ok := likeMap[int64(*v.Id)]; ok {
					isLiked = pointy.GetPointer(likeStatus.Status > 0)
					likeCount = pointy.GetPointer(uint64(likeStatus.Count))
				}
			}
			var statusText *string
			var author *types.AuthorInfo
			if private {
				if v.Status != nil {
					statusText = pointy.GetPointer(util.GetStatusText(int32(*v.Status)))
				}
			} else {
				if !skipLevel {
					var levelName *string
					var levelUrl *string
					if userRankMap != nil && v.AuthorRankId != nil && *v.AuthorRankId > 0 {
						if userRank, ok := userRankMap[*v.AuthorRankId]; ok {
							levelName = userRank.Name
							levelUrl = userRank.MediaUrl
						}
					}
					if v.AuthorNickname != nil {
						author = &types.AuthorInfo{
							Id:        v.AuthorId,
							Name:      v.AuthorNickname,
							Avatar:    v.AuthorAvatar,
							Ip:        v.AuthorIP,
							Level:     v.AuthorRankId,
							LevelName: levelName,
							LevelUrl:  levelUrl,
						}
					}
				}
			}

			var commentStatus *bool
			if v.CommentStatus != nil {
				commentStatus = pointy.GetPointer(*v.CommentStatus > 0)
			}
			var createdAt *string
			if v.CreatedAt != nil && len(*v.CreatedAt) > 0 {
				createdAt = pointy.GetPointer(util.GetTimeFromNow(*v.CreatedAt))
			}

			resp.List = append(resp.List, &types.PostInfo{
				Id:            v.Id,
				ContentHtml:   v.PostContent,
				AuthorId:      v.AuthorId,
				ParentId:      v.ParentId,
				Parent:        parent,
				Photos:        photos,
				Status:        v.Status,
				StatusText:    statusText,
				IsLiked:       isLiked,
				LikeCount:     likeCount,
				CommentStatus: commentStatus,
				Author:        author,
				Sticky:        v.Sticky,
				CreatedAt:     createdAt,
				UpdatedAt:     v.CreatedAt,
			})
		}
	}

	if private && req.New != nil && *req.New {
		var userMeta []*userclient.UserMetaInfo
		userMeta = append(userMeta, &userclient.UserMetaInfo{
			Key:   pointy.GetPointer(mqueuex.UserStatisticForumReviewNew), // "_review_new_status"
			Value: pointy.GetPointer("0"),
		})
		l.svcCtx.UserRpc.SetUserMeta(l.ctx, &userclient.SetUserMetaReq{
			UserId:   pointy.GetPointer(userId),
			UserMeta: userMeta,
		})
	}

	return resp, nil
}

func (l *GetPostListLogic) getPerfumeMap(ids []string) (map[uint64]*types.KbEntryInfo, error) {
	if len(ids) == 0 {
		return nil, nil
	}

	preload := "blogBook:Id,Title,Slug;blogMedia:Id,Uid,Url,Thumbnail;blogBookRelation:brand"
	eagerLoad := "blogBook:blogMedia,blogBookRelation"
	res, err := l.svcCtx.BlogRpc.BookList(l.ctx, &blogclient.BookListReq{
		Preload:   preload,
		EagerLoad: eagerLoad,
		EntryIds:  strings.Join(ids, ","),
	})
	if err != nil {
		logrus.Info(fmt.Sprintf("GetPostList getPerfumeMap err: %+v", err))
		return nil, err
	}

	if len(res.Data) > 0 {
		resp := make(map[uint64]*types.KbEntryInfo)
		for _, item := range res.Data {
			var media []*types.TmpMediaInfo
			if len(item.Media) > 0 {
				for _, v := range item.Media {
					media = append(media, &types.TmpMediaInfo{
						Uid:       pointy.GetPointer(uint64(v.Uid)),
						Id:        pointy.GetPointer(strconv.FormatInt(v.Id, 10)),
						Url:       pointy.GetPointer(v.Url),
						Thumbnail: pointy.GetPointer(uint32(v.Thumbnail)),
						AltText:   pointy.GetPointer(v.AltText),
						MetaData:  pointy.GetPointer(v.Meta),
					})
				}
			}
			var brand []*types.KbEntryInfo
			if len(item.Relations) > 0 {
				for _, v := range item.Relations {
					if v.Section == "brand" {
						brand = append(brand, &types.KbEntryInfo{
							Id:    pointy.GetPointer(uint64(v.Id)),
							Title: pointy.GetPointer(v.Title),
							Slug:  pointy.GetPointer(v.Slug),
						})
					}
				}
			}

			resp[uint64(item.Id)] = &types.KbEntryInfo{
				Id:     pointy.GetPointer(uint64(item.Id)),
				Title:  pointy.GetPointer(item.Title),
				Slug:   pointy.GetPointer(item.Slug),
				Media:  media,
				Brands: brand,
			}
		}

		return resp, nil
	}

	return nil, nil
}

func (l *GetPostListLogic) getPostLikeBatch(postIds []string, userId string) map[int64]*forumreaction.ForumReactionStatus {
	forumReaction := forumreaction.NewForumReaction(l.ctx, l.svcCtx, cachex.ForumReviewLike)
	likeMap, err := forumReaction.GetReactionMap(postIds, userId)
	if err != nil {
		logrus.Info(fmt.Sprintf("GetPostList getPostLikeBatch GetReactionMap err: %+v ", err))
		return nil
	}

	// logrus.Info(fmt.Sprintf("GetPostList getPostLikeBatch GetReactionMap : %+v ", likeMap))
	var objectIds []string
	var extraIds []string
	for i, v := range likeMap {
		// logrus.Info(fmt.Sprintf("GetPostList getPostLikeBatch GetReactionMap item %d : %+v ", i, v))
		if v.Status == -1 {
			objectIds = append(objectIds, strconv.FormatInt(i, 10))
		}
		if v.Count == -1 {
			extraIds = append(extraIds, strconv.FormatInt(i, 10))
		}
	}
	if len(objectIds) > 0 || len(extraIds) > 0 {
		logMap, extraMap, err := l.getPostLikeMap(objectIds, userId, extraIds)
		if err != nil {
			logrus.Info(fmt.Sprintf("GetPostList getPostLikeBatch getPostLikeMap err: %+v ", err))
			return nil
		}

		for i, v := range likeMap {
			if v.Status == -1 {
				if status, ok := logMap[i]; ok { // 数据库有记录
					v.Status = status
					forumReaction.InitStatus(
						strconv.FormatInt(i, 10),
						userId,
						strconv.FormatInt(int64(status), 10),
					)
				} else {
					v.Status = 0
					forumReaction.InitStatus(strconv.FormatInt(i, 10), userId, "-1")
				}
			}
			if v.Count == -1 {
				if count, ok := extraMap[i]; ok { // 数据库有记录
					v.Count = count
					forumReaction.InitCount(strconv.FormatInt(i, 10), strconv.FormatInt(count, 10))
				} else {
					v.Count = 0
					forumReaction.InitCount(strconv.FormatInt(i, 10), "0")
				}
			}
			likeMap[i] = v
		}
	}

	return likeMap
}

func (l *GetPostListLogic) getPostLikeMap(
	postIds []string,
	userId string,
	extraIds []string,
) (resp map[int64]int32, extra map[int64]int64, err error) {
	resp = make(map[int64]int32)
	extra = make(map[int64]int64)

	if len(postIds) == 0 && len(extraIds) == 0 {
		return
	}

	var filters []string
	if len(postIds) > 0 {
		filters = append(filters, "PostId,in:"+strings.Join(postIds, ","))
		filters = append(filters, "UserId,equalTo:"+userId)
		filters = append(filters, "Type,equalTo:"+cachex.ForumReviewLike)
	}
	var preFilters []string
	if len(extraIds) > 0 {
		preFilters = append(preFilters, "PostId,in:"+strings.Join(extraIds, ","))
		preFilters = append(preFilters, "Type,equalTo:"+cachex.ForumReviewLike)
	}
	res, err := l.svcCtx.ForumRpc.GetReactionLogList(l.ctx, &forumclient.BaseListReq{
		Preload:         pointy.GetPointer("forumReactionLog:PostId,UserId,Status,Count"),
		Filter:          pointy.GetPointer(strings.Join(filters, ";")),
		PreFilterEntity: pointy.GetPointer(cachex.ForumReviewLike),
		PreFilter:       pointy.GetPointer(strings.Join(preFilters, ";")),
	})
	if err != nil {
		return nil, nil, err
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.PostId == nil || v.Status == nil || *v.PostId == 0 || *v.Status == 0 {
				resp[int64(*v.PostId)] = int32(*v.Status)
			}
		}
	}
	if len(res.Extra) > 0 {
		for _, v := range res.Extra {
			if v.PostId == nil || v.Count == nil || *v.PostId == 0 || *v.Count == 0 {
				extra[int64(*v.PostId)] = int64(*v.Count)
			}
		}
	}

	return
}

func (l *GetPostListLogic) getUserRankMap(userId uint64) map[uint32]*types.UserRankInfo {
	userRank := userrank.NewUserRank(l.ctx, l.svcCtx)
	userRankList, err := userRank.List(userId)
	if err != nil {
		logrus.Info(fmt.Sprintf("GetPostList getUserRankMap err: %+v", err))
		return nil
	}

	if len(userRankList) > 0 {
		resp := make(map[uint32]*types.UserRankInfo)
		for _, v := range userRankList {
			if v.Id != nil && *v.Id > 0 {
				resp[uint32(*v.Id)] = v
			}
		}

		return resp
	}

	return nil
}
